import log4js from 'log4js'
import logsConfig from './config'
//加载配置文件
log4js.configure(logsConfig)
//调用预先定义的日志名称
var resLogger = log4js.getLogger('resLogger')
var errorLogger = log4js.getLogger('errorLogger')
var handleLogger = log4js.getLogger('handleLogger')
var consoleLogger = log4js.getLogger()

// 格式化日志文本 加上日志头尾和换行方便查看 ==>  普通日志、请求日志、响应日志、操作日志、错误日志
var formatText = {
  info(info: any) {
    return `
    ***************info log start ***************
    info detail: 
    ${JSON.stringify(info)}
    *************** info log end ***************
    `
  },
  request(
    req: {
      method: string
      originalUrl: string
      ip: string | number
      query?: any
      body?: any
      [propName: string]: any
    },
    resTime: string
  ) {
    return `
    request method: ${req.method}
    request originalUrl:  ${req.originalUrl}
    request client ip:  ${req.ip}
    request query:  ${
      req.method === 'GET'
        ? JSON.stringify(req.query)
        : JSON.stringify(req.body)
    }
    response time: ${resTime}
    `
  },
  response(ctx: any, resTime: string) {
    let bodyStr = JSON.stringify(ctx.body)
    bodyStr = bodyStr.length > 1000 ? bodyStr.slice(0, 1000)+'....' : bodyStr
    return `
    *************** response log start ***************
    ${formatText.request(ctx.request, resTime)}
    response status: ${ctx.status}
    response body: ${bodyStr}
    *************** response log end ***************
    `
  },
  handle: function (info: any) {
    var logText = new String()
    //响应日志开始
    logText += '\n' + '***************info log start ***************' + '\n'
    //响应内容
    logText +=
      'handle info detail: ' +
      '\n' +
      JSON.stringify(info).replace(/\\n/g, '\n') +
      '\n'
    //响应日志结束
    logText += '*************** info log end ***************' + '\n'
    return logText
  },
  error: function (ctx: any, err: any, resTime: any) {
    var logText = new String()
    //错误信息开始
    logText += '\n' + '*************** error log start ***************' + '\n'
    //添加请求日志
    logText += formatText.request(ctx.request, resTime)
    //错误名称
    logText += 'err name: ' + err.name + '\n'
    //错误信息
    logText += 'err message: ' + err.message + '\n'
    //错误详情
    logText += 'err stack: ' + err.stack + '\n'
    //错误信息结束
    logText += '*************** error log end ***************' + '\n'
    return logText
  },
}

export default {
  //封装普通日志
  logInfo: function (info: any) {
    if (info) {
      consoleLogger.info(formatText.info(info))
    }
  },
  //封装响应日志
  logResponse: function (ctx: any, resTime: string) {
    if (ctx) {
      resLogger.info(formatText.response(ctx, resTime))
    }
  },
  //封装操作日志
  logHandle: function (res: any) {
    if (res) {
      handleLogger.info(formatText.handle(res))
    }
  },
  //封装错误日志
  logError: function (ctx: any, error: any, resTime: string) {
    if (ctx && error) {
      errorLogger.error(formatText.error(ctx, error, resTime))
    }
  },
}
